var app = getApp();
var WxParse = require('../../lib/wxParse/wxParse.js');
var util = require('../../utils/util.js');
var api = require('../../config/api.js');

Page({
  data: {
    id: 0,
    goods: {},
    imglist: [],
    gallery: [],
    edition:[],
    goodprice:0,
    smallimage:'',
    specificationList: [],
    attribute: [],
    issueList: [],
    comment: [],
    brand: {},
    productList: [],
    relatedGoods: [],
    cartGoodsCount: 0,
    userHasCollect: 0,
    number: 1,
    checkedSpecText: '请选择规格数量',
    openAttr: false,
    noCollectImage: "/static/images/icon_collect.png",
    hasCollectImage: "/static/images/icon_collect_checked.png",
    collectBackImage: "/static/images/icon_collect.png",
    Domain: api.Domain
  },
  onShareAppMessage: function () {
    let that=this;
    return {
      title: that.data.goods.goods_name,
      desc: that.data.goods.goods_name,
      path: '/goods/goods?id=' + that.data.id
    }
  },
  getGoodsInfo: function () {
    let that = this;
    let user_id = wx.getStorageSync('userId');
    util.request(api.GoodsDetail, { id: that.data.id, user_id: user_id }).then(function (res) {
      if (res.errno === 0) {
       let collectImage=res.data.is_collect == 1 ? that.data.hasCollectImage : that.data.noCollectImage;
        that.setData({
          goods: res.data,
          imglist: res.data.img_list,
          gallery: res.data.gallery,
          edition: res.data.edition,
          goodprice: res.data.shop_price,
          smallimage: api.Domain+res.data.img_list[0].img_original,
          collectBackImage: collectImage,
          specificationList: res.data.gallery,
          attribute: res.data.attribute,
          issueList: res.data.issue,
          comment: res.data.comment,
          brand: res.data.brand,
          productList: res.data.productList,
          userHasCollect: res.data.userHasCollect
        });
        
        WxParse.wxParse('goodsDetail', 'html', res.data.goods_desc, that);
        WxParse.wxParse('goodsParams', 'html', res.data.goods_params, that);
        /*if (res.data.userHasCollect == 1) {
          that.setData({
            'collectBackImage': that.data.hasCollectImage
          });
        } else {
          that.setData({
            'collectBackImage': that.data.noCollectImage
          });
        }
        WxParse.wxParse('goodsDetail', 'html', res.data.info.goods_desc, that);
        that.getGoodsRelated();*/
      }else{
        util.showErrorToast(res.data);
        wx.switchTab({
          url: '/pages/index/index',
        })
      }
    });

  },
  getGoodsRelated: function () {
    let that = this;
    util.request(api.GoodsRelated, { id: that.data.id }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          relatedGoods: res.data.goodsList,
        });
      }
    });
  },
  selectColor: function (event) {
    let that = this;
    let specPrice = event.currentTarget.dataset.price;
    let specValueId = event.currentTarget.dataset.valueId;
    let goodprice = that.data.goods.shop_price;
    let smallimage = that.data.goods.img_list[0].img_original;
    //判断是否可以点击
    let _specificationList = this.data.gallery;
    for (let i = 0; i < _specificationList.length; i++) {
      if (_specificationList[i].img_id == specValueId) {
        if (_specificationList[i].checked) {
          _specificationList[i].checked = false;
        } else {
          _specificationList[i].checked = true;
          goodprice = Number(goodprice) + Number(specPrice);
          smallimage = _specificationList[i].thumb_url;
        }
      }else{
        if (_specificationList[i].checked) {
          _specificationList[i].checked = false;
        } 
      }
    }
    let edition = this.data.edition;
    for (let i = 0; i < edition.length; i++) {
        if (edition[i].checked===true) {
          goodprice = Number(goodprice) + Number(edition[i].edition_price);
        } 
    }
    //重新计算spec改变后的信息
    this.setData({
      'gallery': _specificationList,
      goodprice: goodprice,
      smallimage:smallimage
    });
  },
  selectVersion: function (event) {
    let that = this; 
    let specPrice = event.currentTarget.dataset.price;
    let specValueId = event.currentTarget.dataset.valueId;
    let goodprice = that.data.goods.shop_price;
    //判断是否可以点击
    //TODO 性能优化，可在wx:for中添加index，可以直接获取点击的属性名和属性值，不用循环
    let _specificationList = this.data.edition;
    for (let i = 0; i < _specificationList.length; i++) {
      if (_specificationList[i].e_id == specValueId) {
        if (_specificationList[i].checked) {
          _specificationList[i].checked = false;
        } else {
          _specificationList[i].checked = true;
          goodprice = Number(goodprice) + Number(specPrice);
        }
      } else {
        if (_specificationList[i].checked) {
          _specificationList[i].checked = false;
        }
      }
    }
    let gallery = this.data.gallery;
    for (let i = 0; i < gallery.length; i++) {
      if (gallery[i].checked === true) {
        goodprice = Number(goodprice) + Number(gallery[i].price);
      }
    } 
    this.setData({
      'edition': _specificationList,
      goodprice: goodprice
    });
  },
  //根据已选的值，计算其它值的状态
  setSpecValueStatus: function () {

  },
  //判断规格是否选择完整
  isCheckedAllSpec: function () {
    return !this.getCheckedSpecValue().some(function (v) {
      if (v.valueId == 0) {
        return true;
      }
    });
  },
  getCheckedSpecKey: function () {
    let checkedValue = this.getCheckedSpecValue().map(function (v) {
      return v.valueId;
    });

    return checkedValue.join('_');
  },
  changeSpecInfo: function () {
    let checkedNameValue = this.getCheckedSpecValue();
    //设置选择的信息
    let checkedValue = checkedNameValue.filter(function (v) {
      if (v.valueId != 0) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v.valueText;
    });
    if (checkedValue.length > 0) {
      this.setData({
        'checkedSpecText': checkedValue.join('　')
      });
    } else {
      this.setData({
        'checkedSpecText': '请选择规格数量'
      });
    }
  },
  getCheckedProductItem: function (key) {
    return this.data.productList.filter(function (v) {
      if (v.goods_specification_ids == key) {
        return true;
      } else {
        return false;
      }
    });
  },
  onLoad: function (options) {
    //页面初始化 options为页面跳转所带来的参数
    this.setData({
      id: parseInt(options.id)
    });
    wx.setNavigationBarTitle({
      title: "商品详情"
    })
    var that = this;
    this.getGoodsInfo();
    let userId = wx.getStorageSync('userId');
    util.request(api.CartGoodsCount, {user_id:userId}).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          cartGoodsCount: res.data
        });
      }
    });
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  switchAttrPop: function () {
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr
      });
    }
  },
  closeAttr: function () {
    this.setData({
      openAttr: false,
    });
  },
  addCannelCollect: function () {
    let that = this;
    let user_id = wx.getStorageSync('userId');
    let goods_id = that.data.goods.goods_id;
    //添加或是取消收藏
    util.request(api.addCollect, {user_id:user_id,goods_id:goods_id})
      .then(function (res) {
        let _res = res;
        if (_res.errno == 0) {
          if (_res.type ==1) {
            that.setData({
              'collectBackImage': that.data.hasCollectImage
            });
          } else {
            that.setData({
              'collectBackImage': that.data.noCollectImage
            });
          }

        } else {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: _res.errmsg,
            mask: true
          });
        }
      });
  },
  openCartPage: function () {
    wx.switchTab({
      url: '/pages/cart/cart',
    });
  },
  addToCart: function () {
    let userId = wx.getStorageSync('userId');
    if(userId==""){
      util.showErrorToast('请先登录');
      wx.redirectTo({
        url: '/pages/auth/login/login',
      })
      return false;
    }
    var that = this;
    if (this.data.openAttr === false && (that.data.gallery.length > 0 || that.data.edition.length>0)) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr
      });
    } else {
      let gallery=that.data.gallery;
      let edition=that.data.edition;
      let select_gallery=[];
      let select_edition=[];
      if(gallery.length>0){
        let num=0;
        for (let i = 0; i < gallery.length; i++) {
          if (gallery[i].checked === true) {
            num+=1;
            select_gallery=gallery[i];
          }
        }
        if(num==0){
          util.showErrorToast('请选择颜色');
          return false;
        }
       }

      if (edition.length > 0) {
        let num2 = 0;
        for (let i = 0; i < edition.length; i++) {
          if (edition[i].checked === true) {
            num2 += 1;
            select_edition=edition[i];
          }
        }
        if (num2 == 0) {
          util.showErrorToast('请选择版本');
          return false;
        }
      }
      let userId = wx.getStorageSync('userId');
      let resdata = {userId:userId,goodsId:this.data.goods.goods_id,number:this.data.number,       select_gallery:select_gallery,select_edition:select_edition};
      //添加到购物车
      util.request(api.CartAdd,resdata).then(function (res) {
          let _res = res;
          if (_res.errno == 0) {
            wx.showToast({
              title: '添加成功'
            });
            that.setData({
              cartGoodsCount: _res.data,
              openAttr: !that.data.openAttr
            });
          } else {
            util.showErrorToast(_res.data);
          }
        });
    }

  },
  cutNumber: function () {
    this.setData({
      number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
    });
  },
  addNumber: function () {
    this.setData({
      number: this.data.number + 1
    });
  },
  buyNow:function(){
    let userId = wx.getStorageSync('userId');
    if (userId == "") {
      util.showErrorToast('请先登录');
      wx.redirectTo({
        url: '/pages/auth/login/login',
      })
      return false;
    }
    var that = this;
    if (this.data.openAttr === false && (that.data.gallery.length > 0 || that.data.edition.length > 0)) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr
      });
    } else {
      let gallery = that.data.gallery;
      let edition = that.data.edition;
      let select_gallery = [];
      let select_edition = [];
      if (gallery.length > 0) {
        let num = 0;
        for (let i = 0; i < gallery.length; i++) {
          if (gallery[i].checked === true) {
            num += 1;
            select_gallery = gallery[i];
          }
        }
        if (num == 0) {
          util.showErrorToast('请选择颜色');
          return false;
        }
      }

      if (edition.length > 0) {
        let num2 = 0;
        for (let i = 0; i < edition.length; i++) {
          if (edition[i].checked === true) {
            num2 += 1;
            select_edition = edition[i];
          }
        }
        if (num2 == 0) {
          util.showErrorToast('请选择版本');
          return false;
        }
      }
       
      let edition_price= select_edition.edition_price ? select_edition.edition_price:'';
      let edition_name= select_edition.edition_name ? select_edition.edition_name:'';
      let gallery_price= select_gallery.price ? select_gallery.price:'';
      let img_desc= select_gallery.img_desc ? select_gallery.img_desc:'';
      let img_id= select_gallery.img_id ? select_gallery.img_id:'';
      let url = "../shopping/checkout/checkout" + "?goodsid=" + this.data.goods.goods_id + "&number=" + this.data.number + "&versions_price=" + edition_price + "&versions_title=" + edition_name + "&color_price=" + gallery_price+ "&color_title=" + img_desc + "&color_id=" +img_id;
      wx.redirectTo({
        url: url
      })
    }
  }
})